package com.miguo.component;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;

import com.miguo.app.AppContext;
import com.miguo.app.AppHelper;
import com.miguo.bean.CategoryBean;
import com.miguo.bean.CategoryBrandBean;
import com.miguo.bean.CategoryThemeBean;
import com.miguo.db.CategoryBrandDB;
import com.miguo.db.CategoryDB;
import com.miguo.db.CategoryThemeDB;
import com.miguo.framework.adapter.BaseAdapterHelper;
import com.miguo.framework.adapter.QuickAdapter;
import com.miguo.framework.view.CustomGridView;
import com.miguo.http.Url;
import com.miguo.plugins.alibaba.BaiChuan;
import com.miguo.ui.R;
import com.miguo.utils.Options;
import com.miguo.utils.ScreenUtils;
import com.mrper.util.ApkUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

/**
 * File Names: CategoryLayout
 * Describe:
 * User: LinXiaoZhi(87100854@qq.com)
 * Date: 2015-07-09
 * Time: 10:09
 */

public class CategoryView extends LinearLayout implements AbsListView.OnScrollListener, AdapterView.OnItemClickListener {

    private Context mContext;
    private Activity mActivity;

    private boolean isAutoScroll;
    private ScrollView mScroll;
    private ListView mListView;
    private List<CategoryBean> mCategoryData;
    private CategoryView.ListAdapter mListAdapter;
    private CustomGridView mGridView;
    private CategoryView.GridAdapter mGridAdapter;
    private LinearLayout mThemeLayout;
    private LinearLayout mThemeHotLayout;
    private LinearLayout mThemeHotBrandLayout;
    private CustomGridView mThemeHotBrandGridView;
    private ThemeHotBrandGridAdapter mThemeHotBrandGridAdapter;
    public int selectParentPosition = 0;
    private DisplayImageOptions mOptions;

    public CategoryView(Context context) {
        super(context);
        mContext = context;
        mActivity = (Activity) context;
        initView();
        initListener();
    }

    public CategoryView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mActivity = (Activity) context;
        initView();
        initListener();
    }

    private void initTheme(int position) {
        List<CategoryThemeBean> Theme = CategoryThemeDB.getInstance(mContext, false).findTheirId(mListAdapter.getItem(position).getId(), 1);
        mThemeLayout.removeAllViews();
        if (Theme.size() > 0) {
            for (int i = 0; i < Theme.size(); i++) {
                final CategoryThemeBean ThemeData = Theme.get(i);
                LinearLayout themeLayout = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.layer_sharing_image, null);
                themeLayout.setPadding(0, ScreenUtils.dip2px(mContext, 5.0F), 0, 0);
                ImageView img = (ImageView) themeLayout.findViewById(R.id.img);
                img.getLayoutParams().height = getThemeImageHeight();
                ImageLoader.getInstance().displayImage(ThemeData.getImage_url(), img, mOptions);
                img.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (ThemeData.getType() == 1) {
                            AppHelper.StartPromotion(mActivity, ThemeData.getTitle(), ThemeData.getImage_url(), ThemeData.getParam(), true);
                        } else {
                            if (ThemeData.getJump_type() == 1 || AppContext.isAilError) {
                                AppHelper.StartWebView(mActivity, ThemeData.getParam());
                            } else {
                                BaiChuan.showPage(mActivity, ThemeData.getTitle(), ThemeData.getParam());
                            }
                        }
                    }
                });
                mThemeLayout.addView(themeLayout);
            }
            mThemeLayout.setVisibility(View.VISIBLE);
        } else {
            mThemeLayout.setVisibility(View.GONE);
        }
    }


    private void initThemeHot(int position) {
        List<CategoryThemeBean> ThemeHot = CategoryThemeDB.getInstance(mContext, false).findTheirId(mListAdapter.getItem(position).getId(), 2);

        mThemeHotLayout.removeAllViews();
        if (ThemeHot.size() > 0) {
            for (int i = 0; i < ThemeHot.size(); i++) {
                final CategoryThemeBean ThemeData = ThemeHot.get(i);
                LinearLayout themeLayout = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.layer_sharing_image, null);
                themeLayout.setPadding(0, ScreenUtils.dip2px(mContext, 5.0F), 0, 0);
                ImageView img = (ImageView) themeLayout.findViewById(R.id.img);
                img.getLayoutParams().height = getThemeImageHeight();
                ImageLoader.getInstance().displayImage(ThemeData.getImage_url(), img, mOptions);
                img.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (ThemeData.getType() == 1) {
                            AppHelper.StartPromotion(mActivity, ThemeData.getTitle(), ThemeData.getImage_url(), ThemeData.getParam(), true);
                        } else {
                            if (ThemeData.getJump_type() == 1 || AppContext.isAilError) {
                                AppHelper.StartWebView(mActivity, ThemeData.getParam());
                            } else {
                                BaiChuan.showPage(mActivity, ThemeData.getTitle(), ThemeData.getParam());
                            }
                        }
                    }
                });
                mThemeHotLayout.addView(themeLayout);
            }
            mThemeHotLayout.setVisibility(View.VISIBLE);
        } else {
            mThemeHotLayout.setVisibility(View.GONE);
        }
    }

    private void initThemeHotBrand(int position) {
        List<CategoryBrandBean> Brand = CategoryBrandDB.getInstance(mContext, false).findTheirId(mListAdapter.getItem(position).getId());
        if (Brand.size() > 0) {
            mThemeHotBrandLayout.setVisibility(View.VISIBLE);
            mThemeHotBrandGridAdapter.addAll(Brand, true);
        } else {
            mThemeHotBrandLayout.setVisibility(View.GONE);
        }
    }

    private void initView() {
        //mOptions = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).bitmapConfig(Bitmap.Config.ARGB_8888).build();
        mOptions = Options.getFadeOptions();
        LayoutInflater.from(mContext).inflate(R.layout.category_layout_base_view, this);
        mListView = (ListView) findViewById(R.id.listView);
        mGridView = (CustomGridView) findViewById(R.id.gridView);
        mListAdapter = new CategoryView.ListAdapter(mContext);
        mListView.setAdapter(mListAdapter);
        mGridAdapter = new CategoryView.GridAdapter(mContext);
        mGridView.setAdapter(mGridAdapter);
        mThemeLayout = (LinearLayout) findViewById(R.id.layout_theme);
        mThemeHotLayout = (LinearLayout) findViewById(R.id.layout_theme_hot);
        mThemeHotBrandLayout = (LinearLayout) findViewById(R.id.layout_theme_hot_brand);
        mThemeHotBrandGridView = (CustomGridView) findViewById(R.id.theme_hot_brand_gridView);
        mThemeHotBrandGridAdapter = new CategoryView.ThemeHotBrandGridAdapter(mContext);
        mThemeHotBrandGridView.setAdapter(mThemeHotBrandGridAdapter);
        mScroll = (ScrollView) findViewById(R.id.category_scroll);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            mScroll.setOverScrollMode(View.OVER_SCROLL_NEVER);
        }
    }

    private void initListener() {
        mListView.setScrollContainer(true);
        mListView.setFocusable(true);
        mListView.setFocusableInTouchMode(true);
        mListView.setOnItemClickListener(this);
        mListView.setOnScrollListener(this);

        mGridView.setScrollContainer(true);
        mGridView.setFocusable(true);
        mGridView.setFocusableInTouchMode(true);
        mGridView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == mListView) {
            if (selectParentPosition == position) {
                return;
            }
            setListAndGridSelect(position);
            if (Build.VERSION.SDK_INT >= 11) {
                isAutoScroll = true;
                mListView.smoothScrollToPositionFromTop(position, 0, 800);
                return;
            }
            mListView.setSelection(position);
        }

        if (parent == mGridView) {
            CategoryBean cate = mGridAdapter.getItem(position);
            String CateName;
            if (cate.getPid() == 0) {
                CateName = mListAdapter.getItem(selectParentPosition).getName();
            } else {
                CateName = cate.getName();
            }
            AppHelper.StartItem(mActivity, CateName, cate.getId() + "", Url.toRoute(Url.Item.List, 1));
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == 0 && isAutoScroll) {
            isAutoScroll = false;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                         int totalItemCount) {

    }

    public void setList(List<CategoryBean> list) {
        mCategoryData = list;
        mListAdapter.addAll(mCategoryData, true);
        setListAndGridSelect(0);
        if (mListView != null) {
            mListView.setSelection(0);
        }
    }

    public void setListAndGridSelect(int position) {
        mScroll.scrollTo(0, 0);
        selectParentPosition = position;
        mListAdapter.notifyDataSetChanged();
        mGridAdapter.addAll(addChildCategoryAll(CategoryDB.getInstance(mContext, false).findPid(mListAdapter.getItem(position).getId())), true);
        initTheme(position);
        initThemeHot(position);
        initThemeHotBrand(position);
    }

    private List<CategoryBean> addChildCategoryAll(List<CategoryBean> list) {
        CategoryBean cate = mListAdapter.getItem(selectParentPosition);
        list.add(0, new CategoryBean(cate.getId(), "全部", cate.getIcon(), cate.getPid(), cate.getOrdid()));
        return list;
    }


    private int measureChildIconImage() {
        if (ScreenUtils.WIDTH == 0) {
            ScreenUtils.setDisplay((Activity) mContext);
        }
        return (int) (ScreenUtils.WIDTH / 5 * 3.6D) / 3;
        //return (int) (ScreenUtils.WIDTH / 5 * 3.6D) / 3 - ScreenUtils.dip2px(mContext, 20.0F);
    }

    private int measureHotBrandIconImage() {
        if (ScreenUtils.WIDTH == 0) {
            ScreenUtils.setDisplay((Activity) mContext);
        }
        return ((int) (ScreenUtils.WIDTH / 5 * 3.6D) - ScreenUtils.dip2px(mContext, 68.0F)) / 3 * 60 / 120;
    }

    private int getMaxLineWidth() {
        if (ScreenUtils.WIDTH == 0) {
            ScreenUtils.setDisplay((Activity) mContext);
        }
        return measureHotBrandIconImage() + ScreenUtils.dip2px(mContext, 40.0F);
    }

    private int getThemeImageHeight() {
        if (ScreenUtils.WIDTH == 0) {
            ScreenUtils.setDisplay((Activity) mContext);
        }
        return ((int) (ScreenUtils.WIDTH / 5 * 3.6D) - ScreenUtils.dip2px(mContext, 20.0F)) * 136 / 420;
    }

    private int getLeftListHeight() {
        if (ScreenUtils.HEIGHT == 0) {
            ScreenUtils.setDisplay((Activity) mContext);
        }
        return ScreenUtils.HEIGHT / 14;
    }

    public class ListAdapter extends QuickAdapter<CategoryBean> {

        public ListAdapter(Context context) {
            super(context, R.layout.category_layout_list_item);
        }

        @Override
        protected void convert(BaseAdapterHelper helper, CategoryBean item) {
            if (selectParentPosition == helper.getPosition()) {
                helper.getView().setBackgroundColor(ApkUtil.getColorById(mContext,R.color.text_red_e51c23));
                helper.setBackgroundColorRes(R.id.category_layout, R.color.white);
                helper.setTextColorRes(R.id.parent_category_name, R.color.text_red_e51c23);
                helper.setVisible(R.id.top_line, View.VISIBLE);
                helper.setVisible(R.id.bottom_line, View.VISIBLE);
            } else {
                helper.getView().setBackgroundColor(ApkUtil.getColorById(mContext,R.color.bg_white_fafafa));
                helper.setBackgroundColorRes(R.id.category_layout, R.color.bg_white_fafafa);
                helper.setTextColorRes(R.id.parent_category_name, R.color.text_black_37);
                helper.setVisible(R.id.top_line, View.INVISIBLE);
                helper.setVisible(R.id.bottom_line, View.INVISIBLE);
            }
            helper.getView().getLayoutParams().height = CategoryView.this.getLeftListHeight();
            helper.setText(R.id.parent_category_name, item.getName());


            //Paint mp = new Paint();
            //mp.setTextSize(12);
            //mp.setStrokeWidth(1);
            //Typeface.NORMAL 常规  Typeface.BOLD 粗体
            //Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
            //mp.setTypeface(font);
            //mp.setFakeBoldText(true);


            //helper.setText(R.id.parent_category_name, item.getName());
            //TextView name = (TextView) helper.getView(R.id.parent_category_name);
            //Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
            //name.setTypeface(font);

            //TextPaint tp = name.getPaint();
            //tp.setFakeBoldText(true);

//            Paint mp = new Paint();
//            mp.setTextSize(12);
//            mp.setStrokeWidth(1);
//            TextPaint tp = name.getPaint();
//            tp.set(mp);
        }
    }

    public class GridAdapter extends QuickAdapter<CategoryBean> {

        public GridAdapter(Context context) {
            super(context, R.layout.category_layout_grid_item);
        }

        @Override
        protected void convert(BaseAdapterHelper helper, CategoryBean item) {
            helper.setText(R.id.child_category_name, item.getName());
            helper.setImageOptions(R.id.child_category_icon, item.getIcon(), mOptions);
            helper.getView(R.id.child_category_icon).getLayoutParams().width = CategoryView.this.measureChildIconImage();
            helper.getView(R.id.child_category_icon).getLayoutParams().height = CategoryView.this.measureChildIconImage();
        }
    }


    class ThemeHotBrandGridAdapter extends QuickAdapter<CategoryBrandBean> {

        public ThemeHotBrandGridAdapter(Context context) {
            super(context, R.layout.category_layout_hot_brand_item);
        }

        @Override
        protected void convert(final BaseAdapterHelper helper, final CategoryBrandBean item) {

            if (helper.getPosition() % 3 != 2) {
                helper.setVisible(R.id.line_right, View.VISIBLE);
            } else {
                helper.setVisible(R.id.line_right, View.INVISIBLE);
            }
            int bottomPosition;
            if (getCount() % 3 != 0) {
                bottomPosition = getCount() / 3 * 3;
            } else {
                bottomPosition = (getCount() / 3 - 1) * 3;
            }
            if (helper.getPosition() < bottomPosition) {
                helper.setVisible(R.id.line_bottom, View.VISIBLE);
            } else {
                helper.setVisible(R.id.line_bottom, View.INVISIBLE);
            }

            helper.getView(R.id.brand_icon).getLayoutParams().height = CategoryView.this.measureHotBrandIconImage();
            helper.getView(R.id.line_right).getLayoutParams().height = CategoryView.this.getMaxLineWidth();

            helper.setImageOptions(R.id.brand_icon, item.getLogo_image_url(), mOptions);
            helper.getView().setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.getType() == 1) {
                        AppHelper.StartBrandItem(mActivity, item.getTitle(), item.getHorz_image_url(), item.getParam(), true);
                    } else {
                        if (item.getJump_type() == 1 || AppContext.isAilError) {
                            AppHelper.StartWebView(mActivity, item.getParam());
                        } else {
                            BaiChuan.showPage(mActivity, item.getTitle(), item.getParam());
                        }
                    }
                }
            });
        }
    }

}